package maven_Txl.maven_txl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *这是一个与记录学生通讯录的类
 * @author GG
 *通过文件方式读取通讯录
 */

public class Tongxl extends ArrayList<Student>{
	
	public Tongxl(){
		//创建空的通讯录
	}
	
	public void tongxunl(File bf){
		try {//在文件中读取通讯录
			FileReader r =new FileReader(bf);
			BufferedReader readBf = new BufferedReader(r);
			String temp;
			while((temp =readBf.readLine())!= null){
				String att[] = temp.split(" ");//读取联系人信息
				this.add(new Student(att[0], att[1], att[2], att[3], att[4]));
			}
			readBf.close();
			r.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print("读取内容失败！");
			e.printStackTrace();
		}
	}
	
	/**
	 * 保存通讯录
	 * @param bf  文件路径字符串
	 */
		public void saveTongxl(File bf){
		Student s;
		try {
			FileWriter w =new FileWriter(bf);
			BufferedWriter writeBf = new BufferedWriter(w);
			//String temp = null;
			Iterator<Student> iter = this.iterator();
			while(iter.hasNext()){
				//String att[] = temp.split(" ");
				//this.add(new Student(att[0], att[1], att[2], att[3], att[4]));
				s = iter.next();//下一个联系人
				s.save(writeBf);
				writeBf.flush();
			}
			writeBf.close();
			w.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print("写入信息失败！");
			e.printStackTrace();
		}
	}
	
	public void addStudent(Student s){
		this.add(s);//增加学生信息
	}
	
	public void removeStu(Student s){
		this.remove(this.indexOf(s));//删除学生信息
	}
	
	public void modifiedStu(Student old,Student newS){
		this.add(this.indexOf(old),newS);//修改学生信息
	}
	
	/**
	 * 查找学生信息
	 * @param name 学生的姓名
	 * @return 无参数
	 */
	public Student[] findStu(String name){
		Iterator<Student> itor =this.iterator();//迭代器
		Student s;
		ArrayList<Student> f = new ArrayList<Student>(0);
		while(itor.hasNext()){
			s = itor.next();
			String sn = s.getName();
			boolean b =  name.matches("["+sn+"]*");//匹配学生姓名
			if(b){//存储搜索到的联系人
				f.add(s);
			}
				
		}
		Student fs[]=new Student[f.size()];
		return f.toArray(fs);
		
		}
		public int getSize(){
			return this.size();
	}
	
	 

}

